package o2o.web.actions.order;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ObjectUtils;
import o2o.cache.comment.OrderCommentMemory;
import o2o.cache.order.OrderGoodsMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.shop.ShopExtraInfoMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.shop.ShopCommentInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.shop.ShopCommentInfoVO;
import o2o.web.actions.shop.ShopMan;
import org.apache.commons.lang.StringUtils;
import o2o.system.data.SYS_SETTINGS;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: @Created by yangtk
 * @Date: @Date 2019/9/17 16:30
 * @Classname: OrderCommentMan
 * @To change this template use File | Settings | File Templates.
 */
public class OrderCommentMan {

    public static final String COMMENT_INFO = "好评!";

    // 系统自动评论
    public static void systemOrderAutoComment() throws Exception {

        // 查询出来所有的 未评论的 指定天数之前
        if (SYS_SETTINGS.ORDER_COMMENT_DEFAULT_DAY == 0) {
            return;
        }
        //
        Long time = DateUtils.getCurrTime() - SYS_SETTINGS.ORDER_COMMENT_DEFAULT_DAY * 24 * 60 * 60 * 1000L;
        Long startTime = time - 2 * 24 * 60 * 60 * 1000L; // 两天
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(PojoTables.OrderInfo)
                .append(" where delFlag = 0 and OrderStatus = ").append(ORDER_STATUS.OVER)
                .append(" and  isRefundApply != 2 and isComment = 0").append(" and userFinishTime < ").append(time)
                .append(" and userFinishTime > ").append(startTime)
                .append(" and orderType in (").append(StringUtils.join(ORDER_TYPE.defaultCommentTypeList, ",")).append(")")
                .append(" order by id ");
        List<OrderInfo> list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql.toString());
        if (list == null || list.size() == 0) {
            return;
        }
        List<OrderCommentInfo> orderCommentInfoList = new ArrayList<>();
        List<ShopCommentInfo> shopCommentInfoList = new ArrayList<>();
        Long cTime = DateUtils.getCurrTime();
        Set<String> needOrderNoSet = new HashSet<>(); // 需要设置的
        for (OrderInfo orderInfo : list) {
            boolean b = orderCommentOne(orderInfo, cTime, orderCommentInfoList, shopCommentInfoList);
            if (b) {
                needOrderNoSet.add(orderInfo.getOrderNo());
            }
        }
        if (orderCommentInfoList == null || orderCommentInfoList.size() == 0) {
            return;
        }
        Set<String> orderNoSet = orderCommentInfoList.stream().map(a -> a.getOrderNo()).collect(Collectors.toSet());
        // 上面所有的订单评论已经组装完成了  然后对不同的数据进行保存 并更新数据
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection(true);
            // 插入评论
            saveOrderCommentList(orderCommentInfoList, cTime, con);
            // 修改订单未已经评论了
            updateOrderInfoCommentState(orderNoSet, con);
            con.commit();
        } catch (Exception e) {
            UserDaoSql.getInstance().rollback(con);
            throw e;
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        // 将订单设置为已经评论了
        OrderInfoMemory.getInstance().setComment(orderNoSet);
        //保存店铺的评论并且设置店铺评分
        if (shopCommentInfoList != null && shopCommentInfoList.size() > 0) {
            Map<Long, List<ShopCommentInfo>> map = shopCommentInfoList.stream().collect(Collectors.groupingBy(ShopCommentInfo::getShopId));
            Connection con2 = null;
            try {
                con2 = UserDaoSql.getInstance().getConnection(true);
                saveShopCommentList(shopCommentInfoList, cTime, con2);
                updateShopScore(map, con2);
                con2.commit();
            } catch (Exception e) {
                UserDaoSql.getInstance().rollback(con2);
                throw e;
            } finally {
                UserDaoSql.getInstance().close(con2);
            }
            // 缓存
            for (Long shopId : map.keySet()) {
                //修改店铺星级
                ShopExtraInfoMemory.getInstance().addOrModify(shopId);
                // 店铺的评论
                List<ShopCommentInfo> infos = map.get(shopId);
                if (infos != null && infos.size() > 0) {
                    for (ShopCommentInfo info : infos) {
                        //修改店铺评论
                        ShopMemory.getInstance().setComment(info.getShopId(), info);
                    }
                }
            }
        }
    }

    // 单个订单评论
    public static boolean orderCommentOne(OrderInfo orderInfo, Long cTime, List<OrderCommentInfo> orderCommentInfoList, List<ShopCommentInfo> shopCommentInfoList) throws SQLException {
        if (orderInfo == null) {
            return false;
        }
        List<OrderCommentInfo> tempOrderCommentList = new ArrayList<>();
        List<ShopCommentInfo> tempShopOrderCommentList = new ArrayList<>();

        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(orderInfo.getUsername());
        Map<String, OrderCommentInfo> commentInfoMap = OrderCommentMemory.getInstance().getOrderCommentListByOrderNoV2(orderInfo.getOrderNo());
        if (commentInfoMap == null) {
            commentInfoMap = new HashMap<>();
        }
        if (orderInfo.getOrderType() == ORDER_TYPE.DAI_GOU
                || orderInfo.getOrderType() == ORDER_TYPE.PAO_TUI
                || orderInfo.getOrderType() == ORDER_TYPE.HUO_YUN
                || orderInfo.getOrderType() == ORDER_TYPE.BANG_BAN) {
            if (StringUtils.isEmpty(orderInfo.getPostManUsername())) {
                return false;
            }
            OrderCommentInfo orderCommentInfo = new OrderCommentInfo();
            orderCommentInfo.setCreateTime(cTime).setStar(5).setComment(COMMENT_INFO).setCommentType(ORDER_COMMENT_TYPE.POSTMAN_COMMENT)
                    .setObjUsername(orderInfo.getPostManUsername()).setOrderNo(orderInfo.getOrderNo())
                    .setDelFlag(0).setIsUnknownName(0).setUsername(orderInfo.getUsername());
            CityPostman postman = CityPostmanMemory.getInstance().getPostman(orderCommentInfo.getObjUsername());
            if (postman != null) {
                orderCommentInfo.setObjId(postman.getId());
            }
            if (userInfo != null) {
                orderCommentInfo.setName(userInfo.getName()).setSignPhoto(userInfo.getSignPhoto());
            }
            tempOrderCommentList.add(orderCommentInfo);
            return true;
        }
        // 外卖订单
        // 1. 商家
        if (commentInfoMap != null && commentInfoMap.get(ORDER_COMMENT_TYPE.SHOP_COMMENT + "_" + orderInfo.getShopId()) != null) {

        } else {
            OrderCommentInfo shopComment = new OrderCommentInfo();
            shopComment.setCreateTime(cTime).setStar(5).setComment(COMMENT_INFO).setCommentType(ORDER_COMMENT_TYPE.SHOP_COMMENT)
                    .setObjId(orderInfo.getShopId()).setOrderNo(orderInfo.getOrderNo())
                    .setDelFlag(0).setIsUnknownName(0).setUsername(orderInfo.getUsername());
            if (userInfo != null) {
                shopComment.setName(userInfo.getName()).setSignPhoto(userInfo.getSignPhoto());
            }
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            if (shopInfo != null) {
                shopComment.setObjUsername(shopInfo.getOwnUsername());
                // 1. 商户
                ShopCommentInfo shopCommentInfo = new ShopCommentInfo();
                try {
                    ObjectUtils.copyPropertiesExclude(shopComment, shopCommentInfo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                shopCommentInfo.setShopId(orderInfo.getShopId());
                shopCommentInfo.setCreateUser(orderInfo.getUsername());
                ShopCommentInfoVO vo = new ShopCommentInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(shopCommentInfo, vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tempShopOrderCommentList.add(shopCommentInfo);
            }
            tempOrderCommentList.add(shopComment);
        }

        // 2. 评论骑手的
        if (orderInfo.getIsZiQu() == 0) {
            if (orderInfo.getShopSelfPost() == 1) {
                // 店铺
            } else {
                // 配送的话
                if (StringUtils.isNotEmpty(orderInfo.getPostManUsername())) {
                    CityPostman postman = CityPostmanMemory.getInstance().getPostman(orderInfo.getPostManUsername());
                    OrderCommentInfo postmanComment = new OrderCommentInfo();
                    postmanComment.setCreateTime(cTime).setStar(5).setComment(COMMENT_INFO).setCommentType(ORDER_COMMENT_TYPE.POSTMAN_COMMENT)
                            .setObjUsername(orderInfo.getPostManUsername()).setOrderNo(orderInfo.getOrderNo())
                            .setDelFlag(0).setIsUnknownName(0).setUsername(orderInfo.getUsername());
                    if (userInfo != null) {
                        postmanComment.setName(userInfo.getName()).setSignPhoto(userInfo.getSignPhoto());
                    }
                    if (postman == null) {

                        tempOrderCommentList.add(postmanComment);
                    } else {
                        if (commentInfoMap != null && commentInfoMap.get(ORDER_COMMENT_TYPE.POSTMAN_COMMENT + "_" + postman.getId()) != null) {

                        } else {
                            postmanComment.setObjId(postman.getId());
                        }
                        tempOrderCommentList.add(postmanComment);
                    }
                }
            }
            // 二级配送
            if (StringUtils.isNotEmpty(orderInfo.getSecondaryPostManUsername())) {
                CityPostman postman = CityPostmanMemory.getInstance().getPostman(orderInfo.getSecondaryPostManUsername());
                OrderCommentInfo secondaryPostmanComment = new OrderCommentInfo();
                secondaryPostmanComment.setCreateTime(cTime).setStar(5).setComment(COMMENT_INFO).setCommentType(ORDER_COMMENT_TYPE.SEC_POSTMAN_COMMENT)
                        .setObjUsername(orderInfo.getSecondaryPostManUsername()).setOrderNo(orderInfo.getOrderNo())
                        .setDelFlag(0).setIsUnknownName(0).setUsername(orderInfo.getUsername());
                if (userInfo != null) {
                    secondaryPostmanComment.setName(userInfo.getName()).setSignPhoto(userInfo.getSignPhoto());
                }
                if (postman == null) {
                    tempOrderCommentList.add(secondaryPostmanComment);
                } else {
                    if (commentInfoMap != null && commentInfoMap.get(ORDER_COMMENT_TYPE.SEC_POSTMAN_COMMENT + "_" + postman.getId()) != null) {

                    } else {
                        commentInfoMap.put(ORDER_COMMENT_TYPE.SEC_POSTMAN_COMMENT + "_" + postman.getId(), secondaryPostmanComment);
                        secondaryPostmanComment.setObjId(postman.getId());
                        tempOrderCommentList.add(secondaryPostmanComment);
                    }
                }
            }
        }
        // 3.0 商品的 评论商品的
        List<OrderGoods> orderGoodsList = OrderGoodsMemory.getInstance().listOfOrderNo(orderInfo.getOrderNo());
        if (orderGoodsList != null && orderGoodsList.size() > 0) {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            for (OrderGoods orderGoods : orderGoodsList) {
                if (orderGoods == null) {
                    continue;
                }
                if (commentInfoMap != null && commentInfoMap.get(ORDER_COMMENT_TYPE.GOODS_COMMENT + "_" + orderGoods.getGoodsId()) != null) {

                } else {
                    OrderCommentInfo goodsOrderComment = new OrderCommentInfo();
                    goodsOrderComment.setCreateTime(cTime).setStar(5).setComment(COMMENT_INFO).setCommentType(ORDER_COMMENT_TYPE.GOODS_COMMENT)
                            .setObjId(orderGoods.getGoodsId()).setOrderNo(orderInfo.getOrderNo())
                            .setDelFlag(0).setIsUnknownName(0).setUsername(orderInfo.getUsername());
                    if (shopInfo != null) {
                        goodsOrderComment.setObjUsername(shopInfo.getOwnUsername());
                    } else {
                        goodsOrderComment.setObjUsername("");
                    }
                    tempOrderCommentList.add(goodsOrderComment);
                    commentInfoMap.put(ORDER_COMMENT_TYPE.GOODS_COMMENT + "_" + orderGoods.getGoodsId(), goodsOrderComment);
                }
            }
        }
        if (tempOrderCommentList != null && tempOrderCommentList.size() > 0) {
            orderCommentInfoList.addAll(tempOrderCommentList);
        }
        if (tempShopOrderCommentList != null && tempShopOrderCommentList.size() > 0) {
            shopCommentInfoList.addAll(tempShopOrderCommentList);
        }
        return true;
    }

    // 保存存储的OrderComment
    public static boolean saveOrderCommentList(List<OrderCommentInfo> list, Long cTime, Connection con) throws SQLException {
        if (list == null || list.size() == 0) {
            return true;
        }
        StringBuffer infoSb = new StringBuffer(" INSERT INTO ").append(PojoTables.ORDER_COMMENT)
                .append(" (orderNo,commentType,objUsername,objId,star,")   // 5
                .append("isUnknownName,username,name,signPhoto,delFlag,")  //5
                .append("comment,createTime)") //1
                .append("values(?,?,?,?,?,")
                .append("?,?,?,?,?,")
                .append("?,?)");
        PreparedStatement infoPre = null;
        infoPre = con.prepareStatement(infoSb.toString());
        for (OrderCommentInfo info : list) {
            infoPre.setString(1, info.getOrderNo());
            infoPre.setInt(2, info.getCommentType());
            infoPre.setString(3, getString(info.getObjUsername()));
            infoPre.setLong(4, getLong(info.getObjId()));
            infoPre.setInt(5, info.getStar());
            infoPre.setLong(6, info.getIsUnknownName());
            infoPre.setString(7, getString(info.getUsername()));
            infoPre.setString(8, getString(info.getName()));
            infoPre.setString(9, getString(info.getSignPhoto()));
            infoPre.setInt(10, info.getDelFlag());
            infoPre.setString(11, getString(info.getComment()));
            infoPre.setLong(12, cTime);
            infoPre.addBatch();
        }
        // 添加
        infoPre.executeBatch();
        return true;
    }

    // 修改订单已经评论的状态
    public static void updateOrderInfoCommentState(Set<String> orderNoSet, Connection con) throws SQLException {
        if (orderNoSet == null || orderNoSet.isEmpty()) {
            return;
        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.OrderInfo).append(" set ")
                .append(" isComment = 1 ,updateUser ='").append("admin'")
                .append(" where delFlag = 0 and  orderNo in(").append(StringUtils.join(orderNoSet, ",")).append(")");
        UserDaoSql.getInstance().executeBySql(sql.toString(), con);
    }

    // 保存店铺的评论到店铺上
    public static boolean saveShopCommentList(List<ShopCommentInfo> list, Long cTime, Connection con) throws SQLException {
        if (list == null || list.size() == 0) {
            return true;
        }
        StringBuffer infoSb = new StringBuffer(" INSERT INTO ").append(PojoTables.ShopComment)
                .append(" (orderNo,shopId,star,comment,isUnknownName,")   // 5
                .append("createUser,name,signPhoto,delFlag,createTime)")  //5
                .append("values(?,?,?,?,?,")
                .append("?,?,?,?,?)");
        PreparedStatement infoPre = null;
        infoPre = con.prepareStatement(infoSb.toString());
        for (ShopCommentInfo info : list) {
            infoPre.setString(1, info.getOrderNo());
            infoPre.setLong(2, info.getShopId());
            infoPre.setInt(3, info.getStar());
            infoPre.setString(4, getString(info.getComment()));
            infoPre.setInt(5, info.getIsUnknownName());
            infoPre.setString(6, getString(info.getCreateUser()));
            infoPre.setString(7, getString(info.getName()));
            infoPre.setString(8, getString(info.getSignPhoto()));
            infoPre.setInt(9, 0);
            infoPre.setLong(10, cTime);
            infoPre.addBatch();
        }
        // 添加
        infoPre.executeBatch();
        return true;
    }

    // 更新对店铺的评论
    public static void updateShopScore(Map<Long, List<ShopCommentInfo>> map, Connection con) throws SQLException {
        if (map == null || map.isEmpty()) {
            return;
        }
        for (Long shopId : map.keySet()) {
            ShopMan.addShopScore(shopId, "admin", map.get(shopId), con);
        }
    }


    // -------------------------------- util ----------------------------------
    public static String getString(String val) {
        if (val == null) {
            val = "";
        }
        return val;
    }

    public static Long getLong(Long l) {
        if (l == null) {
            l = 0L;
        }
        return l;
    }


}
